# -*- coding: utf-8 -*-
"""
Created on Thu Aug 25 10:28:12 2022

@author: xiong
"""

import pika
import json
import logging
logger = logging.getLogger("facebook_spider")

class MqPusher():
    valid = True
    def __init__(self,username,password,host,port,virtual_host,queue):
        self.queue = queue
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        pika.PlainCredentials(username=username,password=password) 
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=host,port=port ,virtual_host = virtual_host))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=self.queue,passive=True)
        
    def flash_connect(self):
        pika.PlainCredentials(username=self.username,password=self.password) 
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host,port=self.port ,virtual_host = self.virtual_host))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=self.queue,passive=True)
        
    def provide(self,data):
        if self.valid:
            self.flash_connect()
            self.channel.basic_publish(exchange='',routing_key=self.queue,body=json.dumps(data))
        else:
            logger.info("channal is not valid")
